const Report = require('../models/report');
const User = require('../models/user');
const Product = require('../models/product');
const Order = require('../models/order');

const reportController = {
  // 创建举报
  async createReport(req, res, next) {
    try {
      const reporterId = req.user.userId;
      const { type, targetId, reason, description } = req.body;

      // 验证被举报对象是否存在
      let target;
      switch (type) {
        case 'product':
          target = await Product.findById(targetId);
          break;
        case 'user':
          target = await User.findById(targetId);
          break;
        case 'order':
          target = await Order.findById(targetId);
          break;
      }

      if (!target) {
        return res.status(404).json({
          success: false,
          message: '举报对象不存在'
        });
      }

      // 不能举报自己
      if (type === 'user' && targetId === reporterId) {
        return res.status(400).json({
          success: false,
          message: '不能举报自己'
        });
      }

      // 检查是否已经提交过相同举报
      const existingReport = await Report.findOne({
        reporter: reporterId,
        type,
        targetId,
        status: { $in: ['待处理', '处理中'] }
      });

      if (existingReport) {
        return res.status(400).json({
          success: false,
          message: '您已提交过相同举报，请勿重复提交'
        });
      }

      // 创建举报记录
      const report = new Report({
        reporter: reporterId,
        type,
        targetId,
        reason,
        description
      });

      await report.save();

      res.status(201).json({
        success: true,
        message: '举报已提交',
        data: { report }
      });
    } catch (error) {
      next(error);
    }
  },

  // 获取我的举报列表
  async getMyReports(req, res, next) {
    try {
      const userId = req.user.userId;
      const { page = 1, limit = 10, status, type } = req.query;

      const query = { reporter: userId };
      if (status) query.status = status;
      if (type) query.type = type;

      const skip = (Number(page) - 1) * Number(limit);

      // 获取基础报告数据，不使用refPath
      const [reportsBase, total] = await Promise.all([
        Report.find(query)
          .skip(skip)
          .limit(Number(limit))
          .sort({ createdAt: -1 })
          .populate('reporter', 'username avatar')
          .populate('handler', 'username'),
        Report.countDocuments(query)
      ]);

      // 手动处理不同类型的目标对象
      const reports = await Promise.all(reportsBase.map(async (report) => {
        const reportObj = report.toObject();

        // 根据举报类型选择不同的模型
        if (report.type === 'product') {
          const product = await Product.findById(report.targetId)
            .select('title price status')
            .lean();
          reportObj.targetId = product;
        } else if (report.type === 'user') {
          const user = await User.findById(report.targetId)
            .select('username status')
            .lean();
          reportObj.targetId = user;
        } else if (report.type === 'order') {
          const order = await Order.findById(report.targetId)
            .select('status price')
            .lean();
          reportObj.targetId = order;
        }

        return reportObj;
      }));

      res.json({
        success: true,
        data: {
          reports,
          total,
          page: Number(page),
          totalPages: Math.ceil(total / Number(limit))
        }
      });
    } catch (error) {
      next(error);
    }
  },

  // 管理员获取举报列表
  async getAllReports(req, res, next) {
    try {
      const {
        page = 1,
        limit = 10,
        status,
        type,
        reason,
        startDate,
        endDate,
        sort = 'createdAt',
        order = 'desc'
      } = req.query;

      const query = {};
      if (status) query.status = status;
      if (type) query.type = type;
      if (reason) query.reason = reason;

      // 添加日期范围筛选
      if (startDate || endDate) {
        query.createdAt = {};
        if (startDate) {
          query.createdAt.$gte = new Date(startDate);
        }
        if (endDate) {
          query.createdAt.$lte = new Date(endDate);
        }
      }

      const skip = (Number(page) - 1) * Number(limit);

      // 处理排序
      const sortOption = {};
      sortOption[sort] = order === 'asc' ? 1 : -1;

      // 获取基础报告数据
      const [reportsBase, total] = await Promise.all([
        Report.find(query)
          .skip(skip)
          .limit(Number(limit))
          .sort(sortOption)
          .populate('reporter', 'username avatar studentId')
          .populate('handler', 'username'),
        Report.countDocuments(query)
      ]);

      // 手动进行不同类型目标的填充
      const reports = await Promise.all(reportsBase.map(async (report) => {
        const reportObj = report.toObject();

        // 根据举报类型选择不同的模型进行填充
        if (report.type === 'product') {
          const product = await Product.findById(report.targetId)
            .select('title price images status seller')
            .lean();
          reportObj.targetId = product;
        } else if (report.type === 'user') {
          const user = await User.findById(report.targetId)
            .select('username avatar studentId status')
            .lean();
          reportObj.targetId = user;
        } else if (report.type === 'order') {
          const order = await Order.findById(report.targetId)
            .select('status price buyer seller product')
            .lean();
          reportObj.targetId = order;
        }

        return reportObj;
      }));

      res.json({
        success: true,
        data: {
          reports,
          total,
          page: Number(page),
          totalPages: Math.ceil(total / Number(limit))
        }
      });
    } catch (error) {
      next(error);
    }
  },

  // 管理员处理举报
  async handleReport(req, res, next) {
    try {
      const { id } = req.params;
      const { status, result, action } = req.body;
      const handlerId = req.user.userId;

      const report = await Report.findById(id);
      if (!report) {
        return res.status(404).json({
          success: false,
          message: '举报不存在'
        });
      }

      // 检查举报是否已处理
      if (report.status === '已处理' || report.status === '已驳回') {
        return res.status(400).json({
          success: false,
          message: '该举报已处理完毕'
        });
      }

      // 更新举报状态
      report.status = status;
      report.result = result;
      report.handler = handlerId;
      report.handledAt = new Date();

      await report.save();

      // 如果举报成立，根据指定的action执行对应操作
      if (status === '已处理' && action) {
        switch (report.type) {
          case 'user':
            // 处理用户
            if (action === 'ban') {
              await User.findByIdAndUpdate(report.targetId, {
                status: 'banned',
                statusReason: result,
                statusUpdatedAt: new Date(),
                statusUpdatedBy: handlerId
              });
            } else if (action === 'mute') {
              await User.findByIdAndUpdate(report.targetId, {
                status: 'muted',
                statusReason: result,
                statusUpdatedAt: new Date(),
                statusUpdatedBy: handlerId
              });
            }
            break;

          case 'product':
            // 处理商品
            if (action === 'remove') {
              await Product.findByIdAndUpdate(report.targetId, {
                status: '已下架',
                statusReason: result
              });
            }
            break;

          case 'order':
            // 处理订单
            if (action === 'cancel') {
              await Order.findByIdAndUpdate(report.targetId, {
                status: '已取消',
                cancelReason: result
              });
            }
            break;
        }
      }

      res.json({
        success: true,
        message: '举报处理成功',
        data: { report }
      });
    } catch (error) {
      next(error);
    }
  },

  // 获取举报详情
  async getReportDetail(req, res, next) {
    try {
      const { id } = req.params;
      const userId = req.user.userId;
      const isAdmin = req.user.role === 'admin';

      // 获取基础报告数据，不使用refPath
      const reportBase = await Report.findById(id)
        .populate('reporter', 'username avatar studentId status')
        .populate('handler', 'username');

      if (!reportBase) {
        return res.status(404).json({
          success: false,
          message: '举报不存在'
        });
      }

      // 只有管理员和举报人可以查看详情
      if (!isAdmin && reportBase.reporter._id.toString() !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权查看此举报'
        });
      }

      // 创建可修改的对象
      const report = reportBase.toObject();

      // 根据举报类型选择不同的模型进行填充
      if (reportBase.type === 'product') {
        const product = await Product.findById(reportBase.targetId)
          .populate('seller', 'username avatar studentId status')
          .lean();
        report.targetId = product;
      } else if (reportBase.type === 'user') {
        const user = await User.findById(reportBase.targetId)
          .select('username avatar studentId status')
          .lean();
        report.targetId = user;
      } else if (reportBase.type === 'order') {
        const order = await Order.findById(reportBase.targetId)
          .populate('buyer', 'username avatar studentId status')
          .populate('seller', 'username avatar studentId status')
          .populate('product', 'title price images')
          .lean();
        report.targetId = order;
      }

      res.json({
        success: true,
        data: { report }
      });
    } catch (error) {
      next(error);
    }
  },

  // 获取举报统计信息
  async getReportStats(req, res, next) {
    try {
      // 获取不同状态的举报数量
      const statusStats = await Report.aggregate([
        { $group: { _id: '$status', count: { $sum: 1 } } }
      ]);

      // 获取不同类型的举报数量
      const typeStats = await Report.aggregate([
        { $group: { _id: '$type', count: { $sum: 1 } } }
      ]);

      // 获取不同原因的举报数量
      const reasonStats = await Report.aggregate([
        { $group: { _id: '$reason', count: { $sum: 1 } } }
      ]);

      // 获取最近7天的举报趋势
      const today = new Date();
      const sevenDaysAgo = new Date(today);
      sevenDaysAgo.setDate(today.getDate() - 7);

      const trendData = await Report.aggregate([
        {
          $match: {
            createdAt: { $gte: sevenDaysAgo }
          }
        },
        {
          $group: {
            _id: {
              $dateToString: { format: '%Y-%m-%d', date: '$createdAt' }
            },
            count: { $sum: 1 }
          }
        },
        { $sort: { _id: 1 } }
      ]);

      res.json({
        success: true,
        data: {
          statusStats: statusStats.reduce((acc, item) => {
            acc[item._id] = item.count;
            return acc;
          }, {}),
          typeStats: typeStats.reduce((acc, item) => {
            acc[item._id] = item.count;
            return acc;
          }, {}),
          reasonStats: reasonStats.reduce((acc, item) => {
            acc[item._id] = item.count;
            return acc;
          }, {}),
          trend: trendData
        }
      });
    } catch (error) {
      next(error);
    }
  },

  // 批量处理举报
  async handleReportsBatch(req, res, next) {
    try {
      const { reportIds, status, result } = req.body;
      const handlerId = req.user.userId;

      if (!reportIds || !Array.isArray(reportIds) || reportIds.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请提供有效的举报ID列表'
        });
      }

      // 更新所有指定的举报
      const updateResult = await Report.updateMany(
        {
          _id: { $in: reportIds },
          status: { $in: ['待处理', '处理中'] } // 只处理未完成的举报
        },
        {
          $set: {
            status: status,
            result: result,
            handler: handlerId,
            handledAt: new Date()
          }
        }
      );

      res.json({
        success: true,
        message: `成功处理 ${updateResult.modifiedCount} 条举报`,
        data: {
          modifiedCount: updateResult.modifiedCount,
          matchedCount: updateResult.matchedCount
        }
      });
    } catch (error) {
      next(error);
    }
  }
};

module.exports = reportController; 